package cn.shujuhai.qtadmin.platform.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import cn.shujuhai.qtadmin.platform.domain.SysUser;
import cn.shujuhai.qtadmin.platform.pluging.logging.BusinessType;
import cn.shujuhai.qtadmin.platform.pluging.logging.Logging;
import cn.shujuhai.qtadmin.platform.pluging.result.Result;

/**
 * 用户API
 *
 * @author dch798
 * @date 2021/08/21 22:13
 **/
@RestController
@RequestMapping("user")
public class UserController {
    /**
     *
     * @param oldPassword
     *            当前密码
     * @param newPassword
     *            新密码
     * @return 修改密码结果
     */
    @PostMapping("chgpwd")
    @Logging(title = "修改密码", describe = "修改密码", type = BusinessType.EDIT)
    public Result chgpwd(String oldPassword, String newPassword) {
        UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser userInfo = new SysUser().selectOne(new QueryWrapper<SysUser>().eq("email", userDetails.getUsername()));
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (bCryptPasswordEncoder.matches(oldPassword, userInfo.getPassword())) {
            userInfo.update(new UpdateWrapper<SysUser>().set("password", bCryptPasswordEncoder.encode(newPassword))
                .eq("id", userInfo.getId()));
            return Result.success("密码修改成功");
        } else {
            return Result.failure("密码修改失败，旧密码不正确");
        }
    }
}
